package xddq

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
	D "websocket_apn/define"
	"websocket_apn/proto"

	"github.com/gorilla/websocket"
)

func (xd *XdDriver) starTcpServer(addr string) {
	// 监听本地7777端口
	listener, err := net.Listen("tcp", addr)
	if err != nil {
		fmt.Println("Error listening:", err.Error())
		os.Exit(1)
	}
	fmt.Println("TCP server listening on ", addr)

	go func() {
		for {
			// 等待客户端连接
			conn, err := listener.Accept()
			if err != nil {
				fmt.Println("Error accepting: ", err.Error())
				defer listener.Close()
			}

			// 处理客户端连接
			go xd.handleRequest(conn)
		}
	}()
}

// handleRequest 处理客户端连接，接收数据并打印
func (xd *XdDriver) handleRequest(conn net.Conn) {
	defer conn.Close()

	// 创建一个读取器
	reader := bufio.NewReader(conn)
	for {
		// 读取客户端发送的数据
		message, err := reader.ReadBytes('\n')
		if err != nil {
			fmt.Println("Error reading:", err.Error())
			break
		}
		data := strings.ReplaceAll(string(message), " ", "")
		// 打印接收到的数据
		fmt.Printf("TCP send len[%d] %s", len(data)/2, message)
		hexData, _ := proto.HexStrToBytes(data)
		sendData := &D.Message{
			MessageType:  websocket.BinaryMessage,
			PayloadBytes: hexData,
		}
		xd.Send(sendData)
	}
}
